package org.dalmatian.app.generator.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.io.IoUtil;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import lombok.RequiredArgsConstructor;
import org.dalmatian.common.core.domain.R;
import org.dalmatian.common.mybatis.core.page.PageQuery;
import org.dalmatian.common.mybatis.core.page.TableDataInfo;
import org.dalmatian.common.mybatis.helper.DataBaseHelper;
import org.dalmatian.common.web.core.BaseController;
import org.dalmatian.app.generator.domain.GenTable;
import org.dalmatian.app.generator.domain.GenTableColumn;
import org.dalmatian.app.generator.service.IGenTableService;
import org.noear.solon.annotation.Body;
import org.noear.solon.annotation.Controller;
import org.noear.solon.annotation.Mapping;
import org.noear.solon.annotation.Path;
import org.noear.solon.core.handle.DownloadedFile;
import org.noear.solon.core.handle.MethodType;
import org.noear.solon.validation.annotation.Validated;

/**
 * 代码生成 操作处理
 *
 * @author Lion Li
 */
@RequiredArgsConstructor
@Controller
@Mapping("/tool/gen")
public class GenController extends BaseController {

    private final IGenTableService genTableService;


    /**
     * 查询代码生成列表
     */
    @SaCheckPermission("tool:gen:list")
    @Mapping(value = "/list", method = MethodType.GET)
    public TableDataInfo<GenTable> genList(GenTable genTable, PageQuery pageQuery) {
        return genTableService.selectPageGenTableList(genTable, pageQuery);
    }

    /**
     * 修改代码生成业务
     *
     * @param tableId 表ID
     */
    @SaCheckPermission("tool:gen:query")
    @Mapping(value = "/{tableId}", method = MethodType.GET)
    public R<Map<String, Object>> getInfo(@Path Long tableId) {
        GenTable table = genTableService.selectGenTableById(tableId);
        List<GenTable> tables = genTableService.selectGenTableAll();
        List<GenTableColumn> list = genTableService.selectGenTableColumnListByTableId(tableId);
        Map<String, Object> map = new HashMap<>(3);
        map.put("info", table);
        map.put("rows", list);
        map.put("tables", tables);
        return R.ok(map);
    }

    /**
     * 查询数据库列表
     */
    @SaCheckPermission("tool:gen:list")
    @Mapping(value = "/db/list", method = MethodType.GET)
    public TableDataInfo<GenTable> dataList(GenTable genTable, PageQuery pageQuery) {
        return genTableService.selectPageDbTableList(genTable, pageQuery);
    }

    /**
     * 查询数据表字段列表
     *
     * @param tableId 表ID
     */
    @SaCheckPermission("tool:gen:list")
    @Mapping(value = "/column/{tableId}", method = MethodType.GET)
    public TableDataInfo<GenTableColumn> columnList(@Path("tableId") Long tableId) {
        List<GenTableColumn> list = genTableService.selectGenTableColumnListByTableId(tableId);
        return TableDataInfo.build(list);
    }

    /**
     * 导入表结构（保存）
     *
     * @param tables 表名串
     */
    @SaCheckPermission("tool:gen:import")
    @Mapping(value = "/importTable", method = MethodType.POST)
    public R<Void> importTableSave(String tables, String dataName) {
        String[] tableNames = Convert.toStrArray(tables);
        // 查询表信息
        List<GenTable> tableList = genTableService.selectDbTableListByNames(tableNames, dataName);
        genTableService.importGenTable(tableList, dataName);
        return R.ok();
    }

    /**
     * 修改保存代码生成业务
     */
    @SaCheckPermission("tool:gen:edit")
    @Mapping(method = MethodType.PUT)
    public R<Void> editSave(@Validated @Body GenTable genTable) {
        genTableService.validateEdit(genTable);
        genTableService.updateGenTable(genTable);
        return R.ok();
    }

    /**
     * 删除代码生成
     *
     * @param tableIds 表ID串
     */
    @SaCheckPermission("tool:gen:remove")
    @Mapping(value = "/{tableIds}", method = MethodType.DELETE)
    public R<Void> remove(@Path Long[] tableIds) {
        genTableService.deleteGenTableByIds(tableIds);
        return R.ok();
    }

    /**
     * 预览代码
     *
     * @param tableId 表ID
     */
    @SaCheckPermission("tool:gen:preview")
    @Mapping(value = "/preview/{tableId}", method = MethodType.GET)
    public R<Map<String, String>> preview(@Path("tableId") Long tableId) throws IOException {
        Map<String, String> dataMap = genTableService.previewCode(tableId);
        return R.ok(dataMap);
    }

    /**
     * 生成代码（下载方式）
     *
     * @param tableId 表ID
     */
    @SaCheckPermission("tool:gen:code")
    @Mapping(value = "/download/{tableId}", method = MethodType.GET)
    public void download(HttpServletResponse response, @Path("tableId") Long tableId) throws IOException {
        byte[] data = genTableService.downloadCode(tableId);
        genCode(response, data);
    }

    /**
     * 生成代码（自定义路径）
     *
     * @param tableId 表ID
     */
    @SaCheckPermission("tool:gen:code")
    @Mapping(value = "/genCode/{tableId}", method = MethodType.GET)
    public R<Void> genCode(@Path("tableId") Long tableId) {
        genTableService.generatorCode(tableId);
        return R.ok();
    }

    /**
     * 同步数据库
     *
     * @param tableId 表ID
     */
    @SaCheckPermission("tool:gen:edit")
    @Mapping(value = "/synchDb/{tableId}", method = MethodType.GET)
    public R<Void> synchDb(@Path("tableId") Long tableId) {
        genTableService.synchDb(tableId);
        return R.ok();
    }

    /**
     * 批量生成代码
     *
     * @param tableIdStr 表ID串
     */
    @SaCheckPermission("tool:gen:code")
    @Mapping(value = "/batchGenCode", method = MethodType.GET)
    public DownloadedFile batchGenCode( String tableIdStr) throws IOException {
        String[] tableIds = Convert.toStrArray(tableIdStr);
        byte[] data = genTableService.downloadCode(tableIds);
        return new DownloadedFile("text/json", data, tableIdStr+".zip");
    }

    /**
     * 生成zip文件
     */
    private void genCode(HttpServletResponse response, byte[] data) throws IOException {
        response.reset();
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Expose-Headers", "Content-Disposition");
        response.setHeader("Content-Disposition", "attachment; filename=\"ruoyi.zip\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");
        IoUtil.write(response.getOutputStream(), false, data);
    }

    /**
     * 查询数据源名称列表
     */
    @SaCheckPermission("tool:gen:list")
    @Mapping(value = "/getDataNames", method = MethodType.GET)
    public R<Object> getCurrentDataSourceNameList() {
        try {
            return R.ok(DataBaseHelper.getDataSourceNameList());
        } catch (SQLException e) {
            throw new RuntimeException("初始化数据源失败");
        }
    }
}
